package com.lykj.lib_base.internal.utils

import android.content.Context
import android.os.Environment
import java.io.File

/**
 * ================================================
 * 描述
 * ================================================
 *
 * @author gosha
 * @date 2022/10/12-16:53
 */
 object CacheUtils {
    // 只需要调用getCacheSize方法和ClearCache方法，Context传Activity的实例即可。
    private val TAG = "CacheUtil"


    /**
     * 计算缓存大小
     * @param context
     * @return
     */
    fun getCacheSize(context: Context): String? {
        var cacheSize = getFolderSize(context.cacheDir)
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { // 判断外部存储是否可用
            context.externalCacheDir?.let { cacheSize += getFolderSize(it) }
        }
        return formatSize(cacheSize)
    }


    /**
     * 删除缓存
     * @param context
     */
    fun clearCache(context: Context) {
        deleteFolder(context.cacheDir)
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            context.externalCacheDir?.let { deleteFolder(it) }
        }
    }


    /**
     * 计算文件夹内部文件大小总和
     * @param file 文件夹
     * @return 文件大小总和
     */
    private fun getFolderSize(file: File): Long {
        var size: Long = 0
        try {
            val files: Array<File> = file.listFiles() // 获取文件夹内的文件列表
            for (file1 in files) {
                if (file1.isDirectory()) { // 如果某文件是文件夹，计算内部总和
                    size += getFolderSize(file1)
                } else {
                    size += file1.length()
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return size
    }


    /**
     * 将缓存换算成对应的单位
     * @param cacheSize 缓存大小
     * @return String类型的缓存大小
     */
    private fun formatSize(cacheSize: Long): String? {
        val kb = (cacheSize / 1024).toDouble()
        if (kb < 1) { // cacheSize在 0-1024内， 单位为b
            return (cacheSize / 1024).toString() + "B"
        }
        val mb = kb / 1024
        if (mb < 1) {
            return String.format("%.2f", kb) + "KB"
        }
        val gb = mb / 1024
        return if (gb < 1) {
            String.format("%.2f", mb) + "MB"
        } else String.format("%.2f", gb) + "GB"
    }


    /**
     * 删除文件夹
     * @param dir 文件夹路径
     */
    private fun deleteFolder(dir: File) {
        try {
            val files: Array<File> = dir.listFiles()
            for (file in files) {
                if (file.isDirectory) {
                    deleteFolder(file)
                } else file.delete()
            }
            dir.delete()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}